package org.omegat.imports.adempiere;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 *
 * @author jker
 */
public class TrlTMXSaver {

    private String srcLang;
    private String targetLang;
    private String tmxfile;
    private String version;
    private Map map;

    public TrlTMXSaver(String srcLang, String targetLang, String tmxfile, String version)
    {
        map = new HashMap();
        this.srcLang = srcLang;
        this.targetLang = targetLang;
        this.tmxfile = tmxfile;
        this.version = version;
    }

    public void add(String source, String target)
    {
        map.put(source, target);
    }

    public String replaceSpecialChars(String s) {
        String st = s;
        st = st.replaceAll("&", "&amp;");                                       // NOI18N
        st = st.replaceAll("<", "&lt;");                                        // NOI18N
        st = st.replaceAll(">", "&gt;");                                        // NOI18N
        st = st.replaceAll("\"", "&quot;");                                     // NOI18N
        return st;
    }

    public void save() {
        File f = new File(tmxfile);
        if (f.exists() && f.canWrite()) {
            mergeTmx();
        } else {
            importTmx();
        }
    }

    private void mergeTmx() {
        SAXBuilder builder = new SAXBuilder();
        try {
            Document doc = builder.build(new File(tmxfile));
            Element root = doc.getRootElement();
            Element body = root.getChild("body");
            addAllKeys(body);
            saveToFile(doc);
        } catch (JDOMException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private  void importTmx() {
        Element root = new Element("tmx");
        root.setAttribute("version", "1.1");
        // Added DTD defines
        
        Document doc = new Document(root);
        buildHeader(root);
        buildBody(root);

        saveToFile(doc);
    }

    private void buildHeader(Element root) {
    /*creationtool="OmegaT"
    creationtoolversion="2.0.5"
    segtype="sentence"
    o-tmf="OmegaT TMX"
    adminlang="EN-US"
    srclang="EN-US"
    datatype="plaintext"*/
        Element header = new Element("header");
        header.setAttribute("creationtool", "OmegaT");
        header.setAttribute("creationtoolversion", version);
        header.setAttribute("segtype", "sentence");
        header.setAttribute("o-tmf", "OmegaT TMX");
        header.setAttribute("adminlang", "EN-US");
        header.setAttribute("srclang", "EN-US");
        header.setAttribute("datatype", "plaintext");
        root.addContent(header);
    }

    private void buildBody(Element root) {
        Element body = new Element("body");
        root.addContent(body);
        addAllKeys(body);
    }

    private void addAllKeys(Element body) {
        Object keys[] = map.keySet().toArray();
        for(int i=0; i<keys.length; i++) {
            String key = replaceSpecialChars((String) keys[i]);
            String value = replaceSpecialChars((String) map.get(keys[i]));
            Element tu = new Element("tu");
            Element srcTuv = new Element("tuv");
            Element targetTuv = new Element("tuv");
            Element srcSeg = new Element("seg");
            Element targetSeg = new Element("seg");

            srcTuv.setAttribute("lang", srcLang);  // Source Lang
            srcSeg.setText(key);
            targetTuv.setAttribute("lang", targetLang); // Target Lang
            targetSeg.setText(value);

            srcTuv.addContent(srcSeg);
            tu.addContent(srcTuv);

            targetTuv.addContent(targetSeg);
            tu.addContent(targetTuv);
            body.addContent(tu);
        }
    }

    private void saveToFile(Document doc) {
        Format format = Format.getPrettyFormat();
        XMLOutputter out = new XMLOutputter(format);
        try {
            FileOutputStream fos = new FileOutputStream(new File(tmxfile));
            out.output(doc, fos);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
